package bb.lanxing.device.sgdevcie.storage.fragment;

import static bb.lanxing.service.SyncTaskService.TASK_SYNC_WORKOUT;
import static com.bes.bessdk.BesSdkConstants.BES_CONNECT_ERROR;
import static com.besall.allbase.common.utils.ActivityUtils.showToast;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.RadioButton;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.PopupMenu;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import bb.lanxing.R;
import bb.lanxing.databinding.FragmentXossSGDeviceWorkoutsManagerBinding;
import bb.lanxing.device.sgdevcie.storage.adapter.BBWorkoutsManageAdapter;
import bb.lanxing.devicelist.XZDeviceListActivity;
import bb.lanxing.devices.sync.BesSportProcessor;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.lib.devices.sgsettingentity.workout.Workout;
import bb.lanxing.lib.devices.sgsettingentity.workout.WorkoutState;
import bb.lanxing.lib.devices.sgsettingentity.workout.Workouts;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.mvvm.base.BaseDBFragment;
import bb.lanxing.service.SyncTaskService;
import bb.lanxing.util.Log;
import bb.lanxing.utils.CopyUtil;
import bb.lanxing.view.dialog.CircularProgressDialog;
import com.bes.bessdk.service.base.BBServiceListener;
import com.bes.bessdk.service.base.BesServiceListener;
import com.bes.event.ProgressEvent;
import com.bes.sdk.device.HmDevice;
import com.bes.sdk.message.Constants;
import com.bes.sdk.utils.SettingsJsonUtils;
import com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants;
import com.besall.allbase.bluetooth.service.Protocol.ProtocolService;
import com.besall.allbase.common.utils.FileUtils;
import com.besall.allbase.view.activity.chipstoollevel4.protocol.ProtocolPresenter;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public final class BBWorkoutsManagerFragment extends BaseDBFragment<FragmentXossSGDeviceWorkoutsManagerBinding> implements BesServiceListener, BBServiceListener {
	ExecutorService executor = Executors.newSingleThreadExecutor();
	private static final String TAG = "BBWorkoutsManagerFragment";
	private static final String TRK = "trk";
	private static final String WK = "wk";
	static Workouts mWorkouts = null;
	private final BBWorkoutsManageAdapter bbWorkoutsManageAdapter;
	CircularProgressDialog circularProgressDialog;
	ProgressDialog progressDialog;
	String device_model = null;
	String sn = null;
	Context mContext;
	ProtocolPresenter protocolPresenter = null;
	ProtocolService protocolService = null;
	HashMap<String, WorkoutFile> workoutFileHashMap = new HashMap<>();
	private boolean isEdit;
	private Menu menu;
	private boolean mSelectAll = true;
	private long lastTime = 0;

	private volatile long mProgress;

	public BBWorkoutsManagerFragment() {
		super(R.layout.fragment_xoss_s_g_device_workouts_manager);
		bbWorkoutsManageAdapter = new BBWorkoutsManageAdapter();
		bbWorkoutsManageAdapter.setOnItemLongClickListener((baseQuickAdapter, view, i) -> {
			PopupMenu popupMenu = new PopupMenu(BBWorkoutsManagerFragment.this.requireContext(), view, Gravity.BOTTOM);
			popupMenu.inflate(R.menu.menu_device_sync_item);
			popupMenu.setOnMenuItemClickListener(menuItem -> {
				bbWorkoutsManageAdapter.clearChecked();
				if (menuItem.getItemId() == R.id.device_sync_delete_record) {
					bbWorkoutsManageAdapter.getItem(i).setChecked(true);
					BBWorkoutsManagerFragment.this.deleteChecked();
				} else if (menuItem.getItemId() == R.id.device_sync_re_sync_record) {
					bbWorkoutsManageAdapter.getItem(i).setChecked(true);
					BBWorkoutsManagerFragment.this.reSyncChecked();
				}
				return true;
			});
			popupMenu.show();
			return true;
		});
	}

	/********************************************************
	 update the worklist sync state from the database.
	 *********************************************************/
	public static int updateSyncedWorkoutListFromDb(Workouts newWorkouts) {
		int index;
		int syncedCount = 0;
		if (newWorkouts == null) {
			return 0;
		}
		List<Workout> workoutList = newWorkouts.getWorkoutList();
		if (workoutList == null || workoutList.isEmpty()) {
			Log.e(TAG, "the workoutlist is null or size is 0");
			return 0;
		}
		BesSportProcessor besData = new BesSportProcessor(SmartDevice.TYPE_BES);

		for (index = 0; index < workoutList.size(); index++) {
			Workout workout = workoutList.get(index);
			String wkfileName = workout.getTimestampInYHDHMS() + ".wk";
			boolean result = besData.ifFitFileSynced(wkfileName);
			// Log.e(TAG,"the Workout file name :"+ wkfileName);
			Log.e(TAG, "set new workout filename: " + wkfileName + "result: " + result);
			if (result) {
				workout.setState(WorkoutState.Synced);
				workoutList.set(index, workout);
				mWorkouts.setWorkoutList(workoutList);
				syncedCount++;
			}
		}
		return syncedCount;
	}

	/********************************************************
	 update the worklist sync to watch
	 *********************************************************/
	public static void updateWorkoutJsonSend(Workouts workouts, Context context, ProtocolPresenter presenter) {

		if (workouts == null || context == null || presenter == null) {
			return;
		}
		String workoutsJsonStr = FileUtils.createWorkoutsJsonStr(workouts);
		if (workoutsJsonStr != null) {
			boolean result = FileUtils.writeWorkoutsJsonStrToFile(context, workoutsJsonStr, SettingsJsonUtils.WORKOUT_JSON);
			Log.e(TAG, "updateWorkoutJsonSend: " + result);
			if (result) {
				FileUtils.sendWorkoutListFile(context, presenter);
			}
		}
	}

	@Override public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		mContext = getContext();
		device_model = SettingsJsonUtils.getDeviceModel(mContext);
		sn = SettingsJsonUtils.getSn(mContext);
		protocolPresenter = ProtocolPresenter.getInstance();
		protocolPresenter.setProtocolServiceListener(this);
		protocolPresenter.setProtocolBBServiceListener(this);
		protocolService = protocolPresenter.getProtocolService();
	}

	@Override public void initView(FragmentXossSGDeviceWorkoutsManagerBinding binding) {
		setHasOptionsMenu(true);
		binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
		RecyclerView recyclerView = binding.recyclerView;
		DefaultItemAnimator defaultItemAnimator = new DefaultItemAnimator();
		defaultItemAnimator.setSupportsChangeAnimations(false);
		recyclerView.setItemAnimator(defaultItemAnimator);
		binding.recyclerView.setAdapter(this.bbWorkoutsManageAdapter);
		RadioButton radioButton = binding.radioAll;
		radioButton.setOnClickListener(v -> {
			if (mSelectAll) {
				bbWorkoutsManageAdapter.checkAll();
			} else {
				binding.radioGroup.clearCheck();
				bbWorkoutsManageAdapter.clearChecked();
			}
			mSelectAll = !mSelectAll;
		});
		binding.radioGroup.setOnCheckedChangeListener((radioGroup, i) -> {
			if (i == R.id.radio_synced) {
				bbWorkoutsManageAdapter.checkSynced();
				mSelectAll = true;
			}
		});
		binding.tvReSync.setOnClickListener(view -> reSyncChecked());
		binding.tvDelete.setOnClickListener(view -> deleteChecked());
		Log.e(TAG, "begin get workout list ,track detail.");
		int state = protocolService.getDeviceConnectState();
		if (state != BluetoothProfile.STATE_CONNECTED) {
			showToast(R.string.pls_conn_device);
			return;
		}
		requireActivity().setTitle(R.string.st_workout);
		sendCmdGetTrkSummary();
	}

	private void sendCmdGetTrkSummary() {
		showLoadingDialog();
		protocolPresenter.getBikeWatchDataFromBesClient(ProtocolConstants.BIKEWATCH_get_track_summary, device_model, sn);
	}

	private void parseWorkoutsJson() {
		String DirStr = FileUtils.checkExternalDirectoryPathExist(false, device_model, sn, SettingsJsonUtils.WORKOUTS_FOLDER);
		if (DirStr == null) {
			Log.e(TAG, "the  dir is null,return ");
			return;
		}
		String fileDirStr = FileUtils.checkExternalDirectoryPathExist(true, device_model, sn, SettingsJsonUtils.WORKOUTS_FOLDER, SettingsJsonUtils.WORKOUT_JSON);
		Log.e(TAG, "the file path: " + fileDirStr);
		if (fileDirStr != null) {
			mWorkouts = FileUtils.parseFromFile(fileDirStr, Workouts.class);
			if (mWorkouts == null) {
				Log.e(TAG, "workouts is null,return");
				runOnUIThread(() -> {
					dismissLoadingDialog();
					showToast(R.string.sync_workout_exception);
				});
				return;
			} else {
				List<Workout> workoutList = mWorkouts.converToWorkoutList();
				mWorkouts.setWorkoutList(workoutList);
			}
			runOnUIThread(() -> {
				dismissLoadingDialog();
				if (mWorkouts == null) {
					Log.e(TAG, "the  workouts is null,return");
					return;
				}
				// workout was recreted,need to check the file sync state from db
				if (mWorkouts.getWorkouts_size() > 0) {// mWorkouts.getNeed_update() == 1 &&
					Log.e(TAG, "begin sync the workoutlist from db");
					int count = updateSyncedWorkoutListFromDb(mWorkouts);
					if (count > 0) {
						Log.e(TAG, "the  workouts were synced from db,send new json to watch");
						if (mWorkouts.getNeed_update() == 1) {
							mWorkouts.setNeed_update(0);
						}
						updateWorkoutJsonSend(mWorkouts, mContext, protocolPresenter);
					}
				}

				List<Workout> list = mWorkouts.getWorkoutList();
				FragmentXossSGDeviceWorkoutsManagerBinding binding = getBinding();
				if (null == list || list.isEmpty()) {
					if (binding != null) {
						binding.llBottomPannel.setEnabled(false);
						binding.radioSynced.setEnabled(false);
						binding.radioAll.setEnabled(false);
						binding.tvReSync.setEnabled(false);
						binding.tvDelete.setEnabled(false);
					}
					bbWorkoutsManageAdapter.setList(null);
					bbWorkoutsManageAdapter.setEmptyView(R.layout.empty_view);
				} else {
					if (binding != null) {
						binding.llBottomPannel.setEnabled(true);
						binding.llBottomPannel.setEnabled(true);
						binding.radioSynced.setEnabled(true);
						binding.radioAll.setEnabled(true);
						binding.tvReSync.setEnabled(true);
						binding.tvDelete.setEnabled(true);
					}
					try {
						List<Workout> clonedList = CopyUtil.deepCopy(list);
						clonedList.sort(Comparator.comparingLong(p -> -Long.parseLong(p.getTimestampInYHDHMS())));
						bbWorkoutsManageAdapter.setList(clonedList);
					} catch (IOException | ClassNotFoundException e) {
						throw new RuntimeException(e);
					}
				}
			});
		}
	}

	public static void saveTrkTotalPackageNum(Context context, long totalNum) {
		if (context == null) {
			return;
		}
		android.util.Log.e(TAG, "totalNum: " + totalNum);
		SharedPreferences deviceInfoPrefernce = context.getSharedPreferences("pkg_info", Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = deviceInfoPrefernce.edit();
		editor.putLong("pkg_trk_total_num", totalNum);
		editor.commit();
	}

	private void reSyncChecked() {
		ArrayList<Workout> checkedItem = bbWorkoutsManageAdapter.getCheckedItem();
		if (checkedItem.isEmpty() || getActivity() == null) {
			return;
		}
		int state = protocolService.getDeviceConnectState();
		if (state != BluetoothProfile.STATE_CONNECTED) {
			showToast(R.string.pls_conn_device);
			return;
		}
		List<String> fileNames = new ArrayList<>();
		long totalFileLength = 0;
		for (Workout workout : checkedItem) {
			// workout.setState(WorkoutState.UnSynced);
			Log.e(TAG, "the trk String.valueOf(workout.getTimestampInYHDHMS()): " + workout.getTimestampInYHDHMS());
			fileNames.add(String.valueOf(workout.getTimestampInYHDHMS()));
			totalFileLength += workout.getFileSize();
			saveTrkTotalPackageNum(mContext, totalFileLength);
		}
		Log.e(TAG, "the trk fileNames.size(): " + fileNames.size());
		for (String filename : fileNames) {
			Log.e(TAG, "the trk file name is: " + filename);
		}
		protocolPresenter.getBikeWatchTracksFilesFromBesClient(mContext, fileNames);
		initProgressDialog();
		SharedPreferences deviceInfoPrefernce = mContext.getSharedPreferences("pkg_info", Context.MODE_PRIVATE);
		int pkg_trk_TotalNum = (int) deviceInfoPrefernce.getLong("pkg_trk_total_num", 0);
		showProgressDialog(pkg_trk_TotalNum);
	}

	private void initProgressDialog() {
		progressDialog = new ProgressDialog(getActivity());
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setTitle(R.string.workouts_sync);
		progressDialog.setMessage(getResources().getString(R.string.syncing));
		progressDialog.setCancelable(false);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setButton2(getString(R.string.dialog_btn_cancel), (dialog, which) -> {
			Log.e(TAG, "this is Cancel button");
			userCancelTransfer();
		});
	}

	private void deleteChecked() {
		List<String> fileNames = new ArrayList<>();
		ArrayList<Workout> checkedItem = bbWorkoutsManageAdapter.getCheckedItem();

		int state = protocolService.getDeviceConnectState();
		if (state != BluetoothProfile.STATE_CONNECTED) {
			showToast(R.string.pls_conn_device);
			return;
		}

		if (!checkedItem.isEmpty()) {
			for (Workout workout : checkedItem) {
				Log.e(TAG, "");
				String filename = String.valueOf(workout.getTimestampInYHDHMS());
				Log.e(TAG, "begin collect the checked track file: " + filename);
				fileNames.add(filename);
			}
			if (!checkedItem.isEmpty()) {
				showLoadingDialog();
				Log.e(TAG, "begin delete the track");
				ProtocolPresenter.getInstance().sendBikeWatchDeleteFiles(getContext(), fileNames, ProtocolConstants.BIKEWATCH_DEL_track);
			}
		}
	}

	private void showProgressDialog(int max) {
		lastTime = 0;
		progressDialog.setMax(max);
		progressDialog.setProgress(0);
		progressDialog.show();
	}

	private void updateProgressDialog() {
		if (0 == lastTime) {
			lastTime = System.currentTimeMillis();
		} else {
			long currentTime = System.currentTimeMillis();
			long time = currentTime - lastTime;
			if (time < 500) {
				return;
			} else {
				lastTime = currentTime;
			}
		}

		if (mProgress != 0) {
			if (progressDialog != null) {
				progressDialog.setProgress((int) mProgress);
			}
		}
		Log.e(TAG, "the current mProgress: " + mProgress);
	}

	private void dismissProgressDialog() {
		mProgress = 0;
		lastTime = 0;
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	private void userCancelTransfer() {
		if (protocolPresenter != null) {
			Log.e(TAG, "userCancelTransfer,send give up trans file cmd");
			protocolPresenter.giveUpTransFiles(getContext());
			Log.e(TAG, "userCancelTransfer,send give up trans file cmd,end");
			progressDialog = null;
		}
	}

	private void showLoadingDialog() {
		if (circularProgressDialog == null) {
			circularProgressDialog = new CircularProgressDialog(getActivity(), true, false, null);
		}

		circularProgressDialog.show(R.string.dialog_loading);
	}

	public void dismissLoadingDialog() {
		if (circularProgressDialog != null) {
			circularProgressDialog.dismiss();
			circularProgressDialog = null;
		}
	}

	@Override public void onTotaConnectState(boolean state, HmDevice hmDevice) {
		Log.e(TAG, "workouts manager onTotaConnectState");
	}

	@Override public void onErrorMessage(int msg, HmDevice hmDevice) {
		Log.e(TAG, "workouts manager onErrorMessage,msg: " + msg);
		if (msg == Constants.NO_JSON_FILE_EXIST) {
			runOnUIThread(() -> {
				dismissLoadingDialog();
				bbWorkoutsManageAdapter.setEmptyView(R.layout.empty_view);
			});
		}
	}

	@Override public void onStateChangedMessage(int msg, String msgStr, HmDevice hmDevice) {
		Log.e(TAG, "workouts manager onStateChangedMessage, msgStr: " + msgStr + "msg: " + msg);
		if (msg == BES_CONNECT_ERROR) {
			runOnUIThread(() -> showToast(msgStr));
			Intent intent = new Intent(mContext, XZDeviceListActivity.class);
			if (isAdded()) {
				Log.e(TAG, "is added,start activity");
				startActivity(intent);
			} else {
				Log.e(TAG, "is not added,start activity");
				// getActivity().startActivity(intent);//finish();
			}
		}
	}

	@Override public void onSuccessMessage(int msg, HmDevice hmDevice) {
		Log.e(TAG, "workouts manager onSuccessMessage, msg: " + msg);
		if (msg == Constants.SAVE_WORKOUT_LIST_FILE_SUCCESS) {
			Log.e(TAG, "workouts manager begin parse workout");
			parseWorkoutsJson();
			Log.e(TAG, "workouts manager end parse workout");
		} else if (msg == Constants.SAVE_WORKOUT_TRK_FILE_SUCCESS) {
			/*
			 * runOnUIThread(new Runnable() {
			 *
			 * @Override public void run() {
			 *
			 * Toast.makeText(mContext,"trk file success",Toast.LENGTH_SHORT).show(); } });
			 */
		} else if (msg == Constants.UPDATE_TRK_FILE_TRANS_PROGRESS) {
			updateProgressDialog();
		} else if (msg == Constants.TOTAL_TRK_FILE_TRANS_SUCCESS) {
			Log.e(TAG, "workouts manager all file has received from the watch");
			runOnUIThread(() -> {
				//try {
				//	Thread.sleep(50);
				//} catch (InterruptedException e) {
				//	throw new RuntimeException(e);
				//}
				// sync
				List<Workout> checkedItem = bbWorkoutsManageAdapter.getCheckedItem();
				List<Workout> list = mWorkouts.getWorkoutList();
				for (Workout workout : list) {
					for (Workout checked : checkedItem) {
						if (workout.getTimestampInYHDHMS().equals(checked.getTimestampInYHDHMS())) {
							workout.setState(WorkoutState.Synced);
						}
					}
				}

				String workoutsJsonStr = FileUtils.createWorkoutsJsonStr(mWorkouts);
				if (workoutsJsonStr != null) {
					boolean result = FileUtils.writeWorkoutsJsonStrToFile(mContext, workoutsJsonStr, SettingsJsonUtils.WORKOUT_JSON);
					if (result) {
						FileUtils.sendWorkoutListFile(mContext, protocolPresenter);
					}

					Log.e(TAG, "create workout json file result: " + result);
				}
				dismissProgressDialog();
				ToastUtils.showShort(R.string.str_sync_success);
				List<Workout> clonedList;
				try {
					clonedList = CopyUtil.deepCopy(list);
					clonedList.sort(Comparator.comparingLong(p -> -Long.parseLong(p.getTimestampInYHDHMS())));
					bbWorkoutsManageAdapter.setList(clonedList);
				} catch (IOException | ClassNotFoundException e) {
					throw new RuntimeException(e);
				}
			});
		}
	}

	@Override public void onBBSMessage(int msg, String params) {
		Log.e(TAG, "onBBSuccessMessage, msg: " + msg + "  params: " + params);
		if (msg == Constants.SAVE_WORKOUT_TRK_FILE_SUCCESS) {
			executor.submit(() -> {
				WorkoutFile workoutFile = parseFileToKey(params);
				if (workoutFile != null && workoutFile.getCount() == 2) {
					BesSportProcessor besData = new BesSportProcessor(SmartDevice.TYPE_BES);
					besData.onStartProcess(workoutFile.wkFileDir, workoutFile.trkFileDir, (fitName, result) -> {
						// 处理回调数据
						Log.e(TAG, "onBBSuccessMessage, fitName: " + fitName + ", result: " + result);
						updateSyncedWorkoutList(fitName, result);
					});
				} else {
					Log.d(TAG, "onBBSuccessMessage not ready");
				}
			});
		} else if (msg == Constants.TOTAL_WORKOUT_TRK_FILE_MISSED_NOT_END) {
			runOnUIThread(() -> {
				showToast(params + getString(R.string.workout_not_exist));
			});
		} else if (msg == Constants.TOTAL_WORKOUT_TRK_FILE_MISSED_END) {
			runOnUIThread(() -> {
				showToast(params + getString(R.string.workout_not_exist));
				dismissProgressDialog();// add for show sync progress dialog
			});
		}
	}

	/********************************************************
	 update the worklist after sync the database.
	 *********************************************************/
	private void updateSyncedWorkoutList(String filename, int result) {

		if (filename == null || !filename.endsWith(".wk")) {
			Log.e(TAG, "the filename is error,return ");
			return;
		}

		List<Workout> currWkList = mWorkouts.getWorkoutList();

		if (currWkList == null || currWkList.isEmpty()) {
			Log.e(TAG, "the currWkList is null,return ");
			return;
		}

		String[] fileNamSplit = filename.split("\\.");
		String syncfileName = fileNamSplit[0];
		Log.e(TAG, "updateSyncedWorkoutList,syncfileName:  " + syncfileName);

		int index;
		for (index = 0; index < currWkList.size(); index++) {
			Workout workout = currWkList.get(index);
			String wkfileName = String.valueOf(workout.getTimestampInYHDHMS());
			// Log.e(TAG,"the Workout file name :"+ wkfileName);
			if (syncfileName.equals(wkfileName)) {
				Log.e(TAG, "updateSyncedWorkoutList,set new workout filename: " + wkfileName);
				if (result == BesSportProcessor.BES_SYNC_FINISHED || result == BesSportProcessor.BES_SYNC_DUPLICATED) {
					workout.setState(WorkoutState.Synced);
				}
				// Log.e(TAG,"updateSyncedWorkoutList,update mWorkouts");
				currWkList.set(index, workout);
				mWorkouts.setWorkoutList(currWkList);
				break;
			}
		}
	}

	/// storage/emulated/0/Android/data/bb.lanxing/files/lanxing/Lanxing/123456/Workouts/20240725095131.trk
	/// storage/emulated/0/Android/data/bb.lanxing/files/lanxing/Lanxing/123456/Workouts/20240725095131.wk
	private WorkoutFile parseFileToKey(String fileDir) {
		String key = null;
		String fileType = null;
		Log.e(TAG, "parseFileToKey ,fileDir: " + fileDir);
		if (fileDir != null && (fileDir.endsWith(".trk") || fileDir.endsWith(".wk"))) {
			String[] fileSplit = fileDir.split("/");
			String fileName = fileSplit[fileSplit.length - 1];
			Log.e(TAG, "fileSplit trk or wk ,fileName:  " + fileName);
			String[] fileNameSplit = fileName.split("\\.");
			key = fileNameSplit[0];
			fileType = fileNameSplit[1];
			Log.e(TAG, "parseFileToKey,the key is: " + key);

			if (!workoutFileHashMap.containsKey(key)) {
				Log.e(TAG, "parseFileToKey,the key does not exist in map,put it into map");
				WorkoutFile workoutFile = new WorkoutFile();
				workoutFile.setKey(key);
				if (fileType.equals(TRK)) {
					workoutFile.setTrkFileDir(fileDir);
				} else if (fileType.equals(WK)) {
					workoutFile.setWkFileDir(fileDir);
				}
				workoutFile.setCount(1);
				workoutFileHashMap.put(key, workoutFile);
			} else {
				Log.e(TAG, "parseFileToKey,the key exist in map,check the count");
				WorkoutFile existWorkoutFile = workoutFileHashMap.get(key);
				int count = existWorkoutFile.getCount();
				if (count == 2) {
					Log.e(TAG, "parseFileToKey,the count is 2,return directly");
					workoutFileHashMap.remove(key);
					return existWorkoutFile;
				}

				if (fileType.equals(TRK)) {
					existWorkoutFile.setTrkFileDir(fileDir);
				} else if (fileType.equals(WK)) {
					existWorkoutFile.setWkFileDir(fileDir);
				}
				if (existWorkoutFile.getWkFileDir() != null && existWorkoutFile.getTrkFileDir() != null) {
					workoutFileHashMap.remove(key);
					existWorkoutFile.setCount(2);
					Log.e(TAG, "parseFileToKey,trk: " + existWorkoutFile.getTrkFileDir() + "wk: " + existWorkoutFile.getWkFileDir());
					return existWorkoutFile;
				}
			}
		}
		Log.e(TAG, "parseFileToKey,return null");
		return null;
	}

	public static class WorkoutFile {
		private String key;
		private String trkFileDir;
		private String wkFileDir;
		private int count = 0;

		public String getKey() {
			return key;
		}

		public void setKey(String key) {
			this.key = key;
		}

		public String getTrkFileDir() {
			return trkFileDir;
		}

		public void setTrkFileDir(String trkFileDir) {
			this.trkFileDir = trkFileDir;
		}

		public String getWkFileDir() {
			return wkFileDir;
		}

		public void setWkFileDir(String wkFileDir) {
			this.wkFileDir = wkFileDir;
		}

		public int getCount() {
			return count;
		}

		public void setCount(int count) {
			this.count = count;
		}
	}

	@Override public void onStop() {
		dismissLoadingDialog();
		SyncTaskService.startSyncService(getActivity(), TASK_SYNC_WORKOUT, SharedManager.getInstance().getAutoUploadMode() == 2);
		EventBus.getDefault().unregister(this);
		super.onStop();
	}

	@Subscribe(threadMode = ThreadMode.ASYNC) public void onMessageEvent(ProgressEvent event) {
		mProgress = event.getProgress();
	}

	@Override public void onStart() {
		super.onStart();
		EventBus.getDefault().register(this);
	}
}
